# -*- coding: utf-8 -*-
# @Time    : 2024/12/4 18:19
# @Author  : sjh
# @Site    :
# @File    : decode video to img.py
# @Comment :
from datetime import datetime

import cv2
import numpy as np
import os
import shutil


def make_clean_folder(path_folder):
    if not os.path.exists(path_folder):
        os.makedirs(path_folder)
    else:
        shutil.rmtree(path_folder)
        os.makedirs(path_folder)


read_filepath_root = './output/20250121_173611'
filename = ['cam1', 'cam2']
for name in filename:
    read_filepath = read_filepath_root + f'/{name}'
    rgb_video_path = os.path.join(read_filepath, 'color_video.avi')
    depth_video_high_path = os.path.join(read_filepath, './depth_video_high.avi')
    depth_video_low_path = os.path.join(read_filepath, './depth_video_low.avi')

    make_clean_folder(os.path.join(read_filepath, 'color'))
    make_clean_folder(os.path.join(read_filepath, 'depth'))

    # 打开RGB视频
    rgb_video = cv2.VideoCapture(rgb_video_path)

    # 打开深度视频
    rgb_video_high = cv2.VideoCapture(depth_video_high_path)
    rgb_video_low = cv2.VideoCapture(depth_video_low_path)

    frame_count = 0

    while True:
        ret_color, color_frame = rgb_video.read()
        if not ret_color:
            print('aaaaaaa')
            break

        ret_high, frame_hith = rgb_video_high.read()
        ret_low, frame_low = rgb_video_low.read()
        if frame_hith is None or frame_low is None:
            print('bbbbbbbbb')
            break

        # 将高八位和第八位组合
        depth_frame = (frame_hith.astype(np.uint16) << 8) | frame_low.astype(np.uint16)

        color_file_name = f'{read_filepath}/color/frame_{frame_count:04d}.jpg'
        cv2.imwrite(color_file_name, color_frame)

        depth_file_name = f'{read_filepath}/depth/frame_{frame_count:04d}.png'
        # depth_frame = cv2.flip(depth_frame, 1)
        cv2.imwrite(depth_file_name, depth_frame[:, :, 0])

        frame_count += 1
    rgb_video.release()
    rgb_video_high.release()
    rgb_video_low.release()
    print('Done!')